//
//  BookListViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/23.
//

#import "BookListViewController.h"
#import "BasicClassListCell.h"
#import "BookClassificationManager.h"
#import "BookClassModel.h"
#import "BookClassCollectionViewCell.h"
#import "BookListManager.h"
#import "BookListModel.h"
#import "BookAddManager.h"
#import "LoginViewController.h"

@interface BookListViewController ()<UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UITableView *leftTableView;
@property(nonatomic,strong)NSMutableArray *classArr;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,assign)NSInteger sel_index;
@property(nonatomic,strong)BookClassificationManager *classificationManager;
@property(nonatomic,strong)UIButton *sureBtn;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)BookListManager *bookListManager;
@property(nonatomic,strong)NSMutableArray *selArr;
@property(nonatomic,strong)BookAddManager *bookAddManager;
@property(nonatomic,assign)CGFloat itemMid;

@end

@implementation BookListViewController

-(BookClassificationManager *)classificationManager{
    if(!_classificationManager){
        _classificationManager = [[BookClassificationManager alloc]init];
        _classificationManager.delegate = self;
    }
    return _classificationManager;
}

-(NSMutableArray *)classArr{
    if(!_classArr){
        _classArr = [NSMutableArray array];
    }
    return _classArr;
}

-(BookListManager *)bookListManager{
    if(!_bookListManager){
        _bookListManager = [[BookListManager alloc]init];
        _bookListManager.delegate = self;
    }
    return _bookListManager;
}

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(NSMutableArray *)selArr{
    if(!_selArr){
        _selArr = [NSMutableArray array];
    }
    return _selArr;
}

-(BookAddManager *)bookAddManager{
    if(!_bookAddManager){
        _bookAddManager = [[BookAddManager alloc]init];
        _bookAddManager.delegate = self;
    }
    return _bookAddManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _sel_index = 0;
    if(isIPAD){
        [self updateItemSpacing];
    }else{
        self.itemMid = floor((self.currentAvailableWidth-108-95*2)/3.0);

    }
    [self createUI];
    [self loadClassData];
   
}

#pragma mark - 获取分类数据
-(void)loadClassData{
    [self.classificationManager loadData];
}

#pragma mark - 获取每个分类书籍
-(void)loadBookData{
    if(self.sel_index < self.classArr.count){
        BookClassModel *model = self.classArr[self.sel_index];
        self.bookListManager.typeId = model.dictDataCode;
        [self.bookListManager loadData];
    }
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    [self.customNavigationBar setTitle:@"选择想要的词书"];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.sureBtn = [[UIButton alloc]init];
    [self.sureBtn setTitle:@"确认" forState:UIControlStateNormal];
    [self.sureBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
    [self.sureBtn setTitleColor:KThemeColor forState:UIControlStateSelected];
    self.sureBtn.titleLabel.font = JPUIFontPingFangSCRegular(16);
    [self.sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.sureBtn.ym_acceptEventInterval = 2.0;
    [self.customNavigationBar addSubview:self.sureBtn];
    [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-11);
        make.height.width.mas_equalTo(@42);
        make.bottom.mas_equalTo(@-1);
    }];
    
    self.leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,108,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT) style:UITableViewStyleGrouped];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.leftTableView.rowHeight = 54;
    self.leftTableView.backgroundColor = KbgColor;
    [self.leftTableView registerClass:NSClassFromString(@"BasicClassListCell") forCellReuseIdentifier:@"BasicClassListCell"];
    self.leftTableView.showsVerticalScrollIndicator = NO;
    self.leftTableView.bounces = NO;
    [self.view addSubview:self.leftTableView];
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0,0,108,kBottomJGH)];
    footerView.backgroundColor = KbgColor;
    self.leftTableView.tableFooterView = footerView;
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(108,kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth-108,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT) collectionViewLayout:layout];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.scrollEnabled = YES;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:NSClassFromString(@"BookClassCollectionViewCell") forCellWithReuseIdentifier:@"BookClassCollectionViewCell"];
    [self.view addSubview:self.collectionView];
    
    
    
}

#pragma mark - 计算并设置 itemMid (cell之间的间距)
- (void)updateItemSpacing{
    //最多显示6个
    CGFloat w = self.currentAvailableWidth-108;
    if(w >= (95*6+20*7)){
        self.itemMid = floor((self.currentAvailableWidth-108-95*6)/7.0);
    }else if (w >= (95*5+20*6)){
        self.itemMid = floor((self.currentAvailableWidth-108-95*5)/6.0);
    }else if (w >= (95*4+20*5)){
        self.itemMid = floor((self.currentAvailableWidth-108-95*4)/5.0);
    }else if (w >= (95*3+20*4)){
        self.itemMid = floor((self.currentAvailableWidth-108-95*3)/4.0);
    }else{
        if(w < (95*2+6)){
            self.itemMid = floor((self.currentAvailableWidth-108-95)/2.0);
        }else{
            self.itemMid = floor((self.currentAvailableWidth-108-95*2)/3.0);
        }
    }
}


#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 获取当前可用宽度并更新布局
        self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
        self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
        self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
        [self updateItemSpacing];
        self.leftTableView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,108,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
        [self.leftTableView reloadData];
        self.collectionView.frame = CGRectMake(108,kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth-108,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
        [self.collectionView reloadData];
            
        });
    }
}

#pragma mark - 确定
-(void)sureBtnClick{
    
//    NSString *loginMode = [[NSUserDefaults standardUserDefaults]objectForKey:@"loginMode"];
//    if(loginMode&&[loginMode isEqualToString:@"4"]){
//        //游客需要登录才能添加词书
//        [self login];
//    }else{
        if(self.selArr.count > 0){
            NSMutableString *str = [NSMutableString string];
            for(NSInteger i = 0;i < self.selArr.count;i++){
                NSString *bookId = self.selArr[i];
                [str appendString:bookId];
                if(i != self.selArr.count-1){
                    [str appendString:@","];
                }
            }
            self.bookAddManager.bookIds = str;
            [self.bookAddManager loadData];
        }
//    }
    
}

#pragma mark - 登录
-(void)login{
    LoginViewController *vc = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BasicClassListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BasicClassListCell"];
    if(indexPath.section < self.classArr.count){
        BookClassModel *model = self.classArr[indexPath.section];
        cell.title = model.dictDataName;
    }
    if(indexPath.section == _sel_index){
        cell.isSel = YES;
    }else{
        cell.isSel = NO;
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.classArr.count;;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 108,10)];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0,0,108,20)];
    [footerView addSubview:bgView];
    if(section == _sel_index){
        footerView.backgroundColor = [UIColor whiteColor];
        bgView.backgroundColor = KbgColor;
        [bgView addRoundedCorners:UIRectCornerTopRight withRadii:CGSizeMake(10, 10)];
    }else{
        if((_sel_index > 0)&&(section == _sel_index-1)){
            bgView.frame = CGRectMake(0,-10,108,20);
            footerView.backgroundColor = [UIColor whiteColor];
            bgView.backgroundColor = KbgColor;
            [bgView addRoundedCorners:UIRectCornerBottomRight withRadii:CGSizeMake(10,10)];
        }else{
            footerView.backgroundColor = KbgColor;
            bgView.backgroundColor = KbgColor;
            [bgView addRoundedCorners:UIRectCornerAllCorners withRadii:CGSizeMake(0,0)];
        }
    }
    footerView.clipsToBounds = YES;
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10.0;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 108,0.00001)];
    headerView.backgroundColor = KbgColor;
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.00001;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _sel_index = indexPath.section;
    [self.leftTableView reloadData];
    [self.dataArr removeAllObjects];
    [self loadBookData];
}

#pragma mark collectionView代理方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BookClassCollectionViewCell *cell= [collectionView dequeueReusableCellWithReuseIdentifier:@"BookClassCollectionViewCell" forIndexPath:indexPath];
    if(indexPath.row < self.dataArr.count){
        BookListModel *model = self.dataArr[indexPath.row];
        if([self.selArr containsObject:model.bookId]){
            model.isSel = YES;
        }else{
            model.isSel = NO;
        }
        cell.model = model;
        __weak typeof(self)self_weak_ = self;
        [cell setSelBlock:^(BOOL isSel) {
            if(isSel == YES){
                [self_weak_.selArr addObject:model.bookId];
            }else{
                [self_weak_.selArr removeObject:model.bookId];
            }
            if(self_weak_.selArr.count > 0){
                self_weak_.sureBtn.selected = YES;
            }else{
                self_weak_.sureBtn.selected = NO;
            }
        }];
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(95,124+30);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
     return UIEdgeInsetsMake(20,self.itemMid,20,self.itemMid);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
     return self.itemMid;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
     return 20;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < self.dataArr.count){
        BookListModel *model = self.dataArr[indexPath.row];
        if([self.selArr containsObject:model.bookId]){
            [self.selArr removeObject:model.bookId];
        }else{
            [self.selArr addObject:model.bookId];
        }
        [self.collectionView reloadData];
        if(self.selArr.count > 0){
            self.sureBtn.selected = YES;
        }else{
            self.sureBtn.selected = NO;
        }
    }
}



#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.classificationManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [BookClassModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        [self.classArr addObjectsFromArray:arr];
        [self.leftTableView reloadData];
        [self loadBookData];
    }
    
    if([manager isEqual:self.bookListManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [BookListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        [self.dataArr addObjectsFromArray:arr];
        [self.collectionView reloadData];
    }
    
    
    if([manager isEqual:self.bookAddManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        [[NSNotificationCenter defaultCenter]postNotificationName:@"AddBookSuccess" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


@end
